package guoanmaker.operator.business.service;

import java.math.BigInteger;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.transaction.Transactional;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import guoanmaker.operator.business.dao.OperatorProviderOrderDao;
import guoanmaker.operator.business.model.OperatorCoupons;
import guoanmaker.operator.business.model.OperatorServerClass;
import guoanmaker.operator.business.model.OperatorUser;
import guoanmaker.operator.business.model.PersonalUser;
import guoanmaker.operator.business.model.PersonalUserCoupon;
import guoanmaker.operator.business.model.ProvideOrderForm;
import guoanmaker.operator.business.model.ReturnResult;
import guoanmaker.operator.business.modelnobind.CouponForOrder;
import guoanmaker.operator.business.modelnobind.OderFormRo;
import guoanmaker.operator.business.modelnobind.UserCoupon;
import guoanmaker.operator.business.repository.OperatorCouponsRepository;
import guoanmaker.operator.business.repository.OperatorServerClassRepository;
import guoanmaker.operator.business.repository.OperatorUserRepository;
import guoanmaker.operator.business.repository.PersonalUserCouponRepository;
import guoanmaker.operator.business.repository.PersonalUserRepository;
import guoanmaker.operator.business.repository.ProvideOrderFormRepository;
import guoanmaker.operator.helper.common.util.BeanPropertyUtil;

@Service
public class OperatorCouponsService {
	
	@Autowired
	private  OperatorCouponsRepository   operatorCouponsRepository;
	
	@Autowired
	private  OperatorUserRepository   operatorUserRepository;
	
	@Autowired
	private OperatorProviderOrderDao  operatorProviderOrderDao;
	
	@Autowired
	private OperatorServerClassRepository   operatorServerClassRepository;
	
	
	@Autowired
	private PersonalUserRepository  personalUserRepository;
	
	@Autowired
	private ProvideOrderFormRepository provideOrderFormRepository;
	
	@Autowired
	private  PersonalUserCouponRepository personalUserCouponRepository;
	
	@PersistenceContext
	EntityManager em;
	
	
	public Page<OperatorCoupons>  operatorCouponsList(Integer page,Integer size,String couponsname,String username,Integer status,String startTime,String endTime){
		Specification<OperatorCoupons> specification=new Specification<OperatorCoupons>() {
			@Override
			public Predicate toPredicate(Root<OperatorCoupons> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
				List<Predicate> lstPredicates = new ArrayList<Predicate>();
				lstPredicates.add(criteriaBuilder.equal(root.get("delestatus"), 0));
				if(StringUtils.isNotEmpty(couponsname)){
					lstPredicates.add(criteriaBuilder.like(root.get("couponsname"), "%" + couponsname + "%"));//模糊查询

				}
				if(StringUtils.isNotEmpty(username)){
					lstPredicates.add(criteriaBuilder.like(root.get("createuser"), "%" + username + "%"));//模糊查询
					
				}
				if(status!=null){
					if(status!=2){
						lstPredicates.add(criteriaBuilder.equal(root.get("iseffect"), status));//等于
					}
				}
				if(startTime!=null&&!startTime.equals("")){
					String dates = startTime; 
					dates = dates.replace("Z", " UTC");//注意是空格+UTC
					SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z");//注意格式化的表达式
					Date date=null;
					try {
						date = format.parse(dates);
						 
					} catch (ParseException e) {
						e.printStackTrace();
					}
					//大于或等于传入时间  
					lstPredicates.add(criteriaBuilder.greaterThanOrEqualTo(root.get("startcouponstime"), date));  
				}
				if(endTime!=null&&!endTime.equals("")){
					String dates = endTime; 
					dates = dates.replace("Z", " UTC");//注意是空格+UTC
					SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z");//注意格式化的表达式
					Date date=null;
					try {
						date = format.parse(dates);
					} catch (ParseException e) {
						e.printStackTrace();
					}
					 //小于或等于传入时间  
					lstPredicates.add(criteriaBuilder.lessThanOrEqualTo(root.get("endcouponstime"), date));  
				}
				Predicate[] arrayPredicates = new Predicate[lstPredicates.size()];
				return criteriaBuilder.and(lstPredicates.toArray(arrayPredicates));
			}
		};
		Sort sort = new Sort(Sort.Direction.DESC, "createdate");
		Pageable pageable = new PageRequest(page, size, sort);
		Page<OperatorCoupons> lists=operatorCouponsRepository.findAll(specification, pageable);
		Double s=0.0;
		Double s1=0.0;
		for (OperatorCoupons operatorCoupons : lists) {
			if(operatorCoupons.getSubamount()!=null){
				if(operatorCoupons.getBeensent()!=0){
					if(operatorCoupons.getCouponstype().equals("0")){
						s=	operatorCoupons.getBeensent()*operatorCoupons.getLapseamount();
					}else if(operatorCoupons.getCouponstype().equals("1")){
						s=	operatorCoupons.getBeensent()*operatorCoupons.getSubamount();
					}else if(operatorCoupons.getCouponstype().equals("3")){
						s=operatorCoupons.getBeensent()*operatorCoupons.getSumlapseamount();
					}
				}else if(operatorCoupons.getBeensent()==0){
					s=0.0;	
				}
				if(operatorCoupons.getBeenused()!=0){
					if(operatorCoupons.getCouponstype().equals("0")){
						s1=	operatorCoupons.getBeenused()*operatorCoupons.getLapseamount();
					}else if(operatorCoupons.getCouponstype().equals("1")){
						s1=	operatorCoupons.getBeenused()*operatorCoupons.getSubamount();
					}else if(operatorCoupons.getCouponstype().equals("3")){
						s1=operatorCoupons.getBeenused()*operatorCoupons.getSumlapseamount();
					}
				}else if(operatorCoupons.getBeenused()==0){
					s1=0.0;
				}
			}
			operatorCoupons.setSentcost(s);
			operatorCoupons.setUsecost(s1);
		}
		return lists;
	}
	
	@Transactional
	public  ReturnResult  addCoupons(OperatorCoupons operatorCoupons,String userid,String id,Integer status){
		ReturnResult  returnResult=new ReturnResult();
		if(status==1){
			if(operatorCoupons!=null){
				if(operatorCoupons.getCouponsname()!=null){
					List<OperatorCoupons> lists=operatorCouponsRepository.selectByCouponsname(operatorCoupons.getCouponsname());
					if(lists.size()>0){
						returnResult.setKey("error");
						returnResult.setValue("优惠券名称不可重复");
					}else{
						Double  s=0.0;//成本
						if(!operatorCoupons.getCouponstype().equals("")&&operatorCoupons.getCouponstype()!=null){
							//直减
							if(operatorCoupons.getCouponstype().equals("0")){
								if(operatorCoupons.getLapseamount()!=null&&operatorCoupons.getIssuenumber()!=0){
									s=operatorCoupons.getLapseamount()*operatorCoupons.getIssuenumber();
								}else if(operatorCoupons.getIssuenumber()==0){
									s=0.0;
								}
							}else if(operatorCoupons.getCouponstype().equals("1")){
								if(operatorCoupons.getSubamount()!=null&&operatorCoupons.getIssuenumber()!=0){
									s=operatorCoupons.getSubamount()*operatorCoupons.getIssuenumber();
								}else if(operatorCoupons.getIssuenumber()==0){
									s=0.0;
								}
							}else if(operatorCoupons.getCouponstype().equals("2")){
								// s=operatorCoupons.get
							}else if(operatorCoupons.getCouponstype().equals("3")){
								if(operatorCoupons.getSumlapseamount()!=null&&operatorCoupons.getIssuenumber()!=0){
									s= operatorCoupons.getSumlapseamount()*operatorCoupons.getIssuenumber();
								}else if(operatorCoupons.getIssuenumber()==0){
									s=0.0;
								}
							}
						}
						operatorCoupons.setTotalcost(s);
						if(operatorCoupons.getStarttime()!=null&&!operatorCoupons.getStarttime().equals("")){
							String dates = operatorCoupons.getStarttime(); 
							dates = dates.replace("Z", " UTC");//注意是空格+UTC
							SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z");//注意格式化的表达式
							Date date=null;
							try {
								date = format.parse(dates);
							} catch (ParseException e) {
								e.printStackTrace();
							}
							operatorCoupons.setStartcouponstime(date);
						}
						if(operatorCoupons.getEndtime()!=null&&!operatorCoupons.getEndtime().equals("")){
							String dates = operatorCoupons.getEndtime(); 
							dates = dates.replace("Z", " UTC");//注意是空格+UTC
							SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z");//注意格式化的表达式
							Date date=null;
							try {
								date = format.parse(dates);
							} catch (ParseException e) {
								e.printStackTrace();
							}
							operatorCoupons.setEndcouponstime(date);
						}
						if(operatorCoupons.getEndoftime()!=null&&!operatorCoupons.getEndoftime().equals("")){
							String dates = operatorCoupons.getEndoftime(); 
							dates = dates.replace("Z", " UTC");//注意是空格+UTC
							SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z");//注意格式化的表达式
							Date date=null;
							try {
								date = format.parse(dates);
							} catch (ParseException e) {
								e.printStackTrace();
							}
							operatorCoupons.setEndofdate(date);
						}
						
						OperatorUser   operatorUser =  operatorUserRepository.findOne(userid);
						if(operatorUser!=null){
							operatorCoupons.setCreateuser(operatorUser.getUsername());
						}
						if(!operatorCoupons.getServerid().equals("")&&operatorCoupons.getServerid()!=null){
							if(operatorCoupons.getServerid().equals("0")){
								operatorCoupons.setServername("全平台");
							}else{
								OperatorServerClass  operatorServerClass=	operatorServerClassRepository.findOne(operatorCoupons.getServerid());
								if(operatorServerClass!=null){
									operatorCoupons.setServername(operatorServerClass.getServerName());	
								}
							}
						}
						operatorCoupons.setDelestatus(0);
						operatorCoupons.setCreatedate(new Date());
						operatorCouponsRepository.save(operatorCoupons);
						returnResult.setKey("success");
						returnResult.setValue("保存成功");
					}
				}else{
					returnResult.setKey("error");
					returnResult.setValue("优惠券名称不可为空");
				}
			}else{
				returnResult.setKey("error");
				returnResult.setValue("保存失败");
			}
		}else if(status==2){
			if(operatorCoupons!=null){
				OperatorCoupons p=	operatorCouponsRepository.findOne(id);
				if(p!=null){
						p.setIseffect(operatorCoupons.getIseffect());
						OperatorUser operatorUser=	operatorUserRepository.findOne(userid);
						if(operatorUser!=null){
							p.setCreateuser(operatorUser.getUsername());
							p.setCreatedate(new Date());
						}
						operatorCouponsRepository.save(p);
						returnResult.setKey("success");
						returnResult.setValue("修改成功");
					}
			}else{
				returnResult.setKey("error");
				returnResult.setValue("修改失败");
			}	
		}
		return  returnResult;
	}
	
	
	public  OperatorCoupons  findbyCouponinfo(String id){
		
		return  operatorCouponsRepository.findOne(id);
	}
	@Transactional
	public  ReturnResult  editCoupons(String id,OperatorCoupons  operatorCoupons,String  userid){
		ReturnResult  returnResult=new ReturnResult();
		if(operatorCoupons!=null){
			OperatorCoupons p=	operatorCouponsRepository.findOne(id);
			if(p!=null){
				if(operatorCoupons.getCouponsname().equals(p.getCouponsname())){
					BeanPropertyUtil.copy(p, operatorCoupons);
					OperatorUser operatorUser=	operatorUserRepository.findOne(userid);
					if(operatorUser!=null){
						p.setCreateuser(operatorUser.getUsername());
					}
					p.setCreatedate(new Date());
					operatorCouponsRepository.save(p);
					returnResult.setKey("success");
					returnResult.setValue("修改成功");
				}else{
						List<OperatorCoupons> lists=operatorCouponsRepository.selectByCouponsname(operatorCoupons.getCouponsname());
						if(lists.size()>0){
							returnResult.setKey("error");
							returnResult.setValue("优惠券名称不可重复");
						}
						else{
							BeanPropertyUtil.copy(p, operatorCoupons);
							OperatorUser operatorUser=	operatorUserRepository.findOne(userid);
							p.setCreateuser(operatorUser.getName());
							operatorCouponsRepository.save(p);
							returnResult.setKey("success");
							returnResult.setValue("修改成功");
						}
				}
			}else{
				returnResult.setKey("error");
				returnResult.setValue("优惠券名称不可为空");
			}
		}else{
			returnResult.setKey("error");
			returnResult.setValue("保存失败");
		}
		return  returnResult;
	}
	@Transactional
	public   ReturnResult  deleteCoupons(String id){
		ReturnResult  returnResult=new ReturnResult();
		OperatorCoupons p=	operatorCouponsRepository.findOne(id);
		if(p!=null){
			p.setDelestatus(1);
			p.setIseffect(0);
			operatorCouponsRepository.save(p);
		}
		returnResult.setKey("success");
		returnResult.setValue("删除成功");
		return returnResult;
	}
	
	public  Map<String, Object> couponstongji(){
		   Map<String, Object>  map =new HashMap<>();
		   //成本共计 x元
		   Double  sumamount=0.0;
		   Double  sumamount1=operatorCouponsRepository.selectByCouponsAmount1();
		   Double  sumamount2=operatorCouponsRepository.selectByCouponsAmount2();
		   Double  sumamount3=operatorCouponsRepository.selectByCouponsAmount3();
		   sumamount=sumamount1+sumamount2+sumamount3;
		   map.put("sumamount", sumamount);
		   //共计发送x张优惠券，	
		   int  sentnum= operatorCouponsRepository.selectByCouponsSentnum();
		   map.put("sentnum", sentnum);
		   //已用x张，
		   int  usednum =operatorCouponsRepository.selectByCouponsusednum();
		   map.put("usednum", usednum);
	       return  map;
	}
	
	
	public List<OperatorCoupons> usedConsponList(){
		//查询可用的优惠券列表
		List<OperatorCoupons> list=	operatorProviderOrderDao.usedConsponList();
		return list;
	}
	public List<OperatorCoupons> usedSignConsponList(){
		//查询可用的优惠券列表（累积签到）
		List<OperatorCoupons> list=	operatorProviderOrderDao.usedSigncumConsponList();
		return list;
	}
	public List<OperatorCoupons> usedSignconseConsponList(){
		//查询可用的优惠券列表（连续签到）
		List<OperatorCoupons> list=	operatorProviderOrderDao.usedSignConsponList();
		return list;
	}
	public List<OperatorCoupons> usedConsponNolimits(){
		//查询没有发行数量限制的可用的优惠券列表
		List<OperatorCoupons> list=	operatorProviderOrderDao.usedConsponNolimits();
		return list;
	}
	
	public   Map<String, Object>  secondServerClass(){
		Map<String, Object>  map =new HashMap<>();
		 List<OperatorServerClass>  list2= operatorServerClassRepository.selectByTwoServerclass();
		 if(list2.size()>0){
			 map.put("twoServerclass", list2);
		 }
		return map;
	}
	
	
	public  Map<String, Object>  statisticsForDayCoupons(String  startdate,String enddate,String id){
		Map<String, Object>  map =new HashMap<>();
		//拿到领券的人数
		String sql = "select  c.* from t_personal_user_coupon c where c.start_date >='"+startdate+"'"
				+ " and c.start_date <='"+enddate+"'  and c.oc_id=:id";
		Query query = em.createNativeQuery(sql, PersonalUserCoupon.class);
		query.setParameter("id", id);
		List<PersonalUserCoupon> enlist = (List<PersonalUserCoupon>) query.getResultList();
		if(enlist.size()>0){
			map.put("couponNum", enlist.size());
		}
		return map;
	}
	
	/**
	 * 该优惠券  用户领取 情况
	 * @param id
	 * @return
	 */
	
	public  List<UserCoupon>  sentUserCoupons(String id){
		List<UserCoupon>  lists=new ArrayList<>();
		String sql = "SELECT u.username ,c.start_date,COUNT(c.oc_id) as coponsnum FROM t_personal_user u "+
                      "LEFT JOIN t_personal_user_coupon c ON u.id = c.user_id WHERE  c.oc_id =:id"+
                       " GROUP BY  u.id order by c.start_date desc ";
		Query query = em.createNativeQuery(sql);
		query.setParameter("id", id);
		List  objecArraytList = query.getResultList();
		for(int i=0;i<objecArraytList.size();i++) {     
			UserCoupon  userCoupon=new UserCoupon();
            Object[] obj = (Object[]) objecArraytList.get(i);
            userCoupon.setPhone((String) obj[0]);
            userCoupon.setAcceptTime( (Date) obj[1]);
            userCoupon.setCoponsnum((BigInteger)obj[2]);
            lists.add(userCoupon);
        }   
		/*List<String>  arr=new ArrayList<>();
		List newList = new  ArrayList(); 
		List<UserCoupon>  lists=new ArrayList<>();
		if(enlist.size()>0){
			for (PersonalUserCoupon personalUserCoupon : enlist) {
				if(personalUserCoupon.getUserId()!=null){
					arr.add(personalUserCoupon.getUserId());
				}
			}
			Set set = new  HashSet<>(); 
			for (String cd:arr) {
				if(set.add(cd)){
					newList.add(cd);
				}
			}
		}
		if(newList.size()>0){
			for (int i = 0; i < newList.size(); i++) {
				String userid=(String) newList.get(i);
				PersonalUser personalUser=personalUserRepository.findOne(userid);
				UserCoupon userCoupon=new UserCoupon();
				if(personalUser!=null){
					userCoupon.setPhone(personalUser.getUsername());
				    int num=	personalUserCouponRepository.findByOcIdandUserId(id,userid);
					userCoupon.setCoponsnum(num);
					userCoupon.setAcceptTime(enlist.get(0).getStart_date());
					lists.add(userCoupon);
				}
			}
		}*/
		return  lists;
	}
	
	public  List<CouponForOrder>  sentUserCouponsOrder(String id){
		List<CouponForOrder> arr=new  ArrayList<>();
		OperatorCoupons  operatorCoupons=	operatorCouponsRepository.findOne(id);
		if(operatorCoupons!=null){
			if(operatorCoupons.getBeenused()==0){
				return arr;
			}else{
				String sql = "select  c.* from t_personal_user_coupon c where "
						+ " c.oc_id=:id";
				Query query = em.createNativeQuery(sql, PersonalUserCoupon.class);
				query.setParameter("id", id);
				List<PersonalUserCoupon> enlist = (List<PersonalUserCoupon>) query.getResultList();
				if(enlist.size()>0){
					for (PersonalUserCoupon personalUserCoupon : enlist) {
						//1代表已使用过优惠券
						if(personalUserCoupon.getIsUsed().equals("1")){
							String  jpql="select o from ProvideOrderForm o   where  o.couponid  like '%"+personalUserCoupon.getId()+"%'";
							Query query1 = em.createQuery(jpql);
							List<ProvideOrderForm> lists = query1.getResultList();
							if(lists.size()>0&&lists!=null){
								for (ProvideOrderForm provideOrderForm : lists) {
									CouponForOrder couponForOrder=new CouponForOrder();
									couponForOrder.setCommdityname(provideOrderForm.getCommodity().getCommodityName());
									couponForOrder.setOrdernum(provideOrderForm.getOrderNumber());
									couponForOrder.setPlaceordertime(provideOrderForm.getPlaceOrderTime());
									arr.add(couponForOrder);
								}
							}
						}
					}
				}
			}
		}
		return arr;
		
	}
	
	

}
